package com.cn.xt.controller.app;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cn.xt.constants.Constants;
import com.cn.xt.controller.BaseController;
import com.cn.xt.entity.CarCompany;
import com.cn.xt.entity.CarInfo;
import com.cn.xt.entity.CarReserveInfo;
import com.cn.xt.service.ICarCompanyService;
import com.cn.xt.service.ICarLogService;
import com.cn.xt.service.ICarReserveInfoService;
import com.cn.xt.utils.HttpUtil;
import com.cn.xt.vo.res.CarInfoQuery;
import com.cn.xt.vo.rsp.CarInfoResult;
import com.cn.xt.service.ICarInfoService;
import com.cn.xt.vo.rsp.ResponseBase;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jakarta.validation.Valid;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author sunyongzheng
 * @date 2021/3/18
 */
@Api(value = "接口")
@RestController
@RequestMapping("/carApp/carInfo")
public class CarInfoAppController extends BaseController {

    @Resource
    private ICarInfoService carInfoService;

    @Resource
    private ICarLogService carLogService;

    @Resource
    private ICarCompanyService carCompanyService;

    @Resource
    private ICarReserveInfoService carReserveInfoService;

    @Value("${car.uploadPath}")
    private String PICTURE_PATH;//图片上传路径


    /**
     * @description 添加车辆
     * @author sunyongzheng
     * @date 2021/3/19 14:03
     */
    @ApiOperation(value = "添加车辆", notes = "添加车辆 ")
    @RequestMapping(value = "/addCar", method = RequestMethod.POST)
    @Transactional
    public ResponseBase addCar(@Valid @RequestBody CarInfo carInfo, BindingResult bindingResult) {
        try {
            // 验证实体输入参数
            ResponseBase validResult = validateField(bindingResult);
            if (validResult != null) {
                return validResult;
            }
            //车牌号查重
            if (duplicateChecking("car_license_plate", carInfo.getCarLicensePlate())) {
                return setResult(Constants.HTTP_RES_CODE_401, localeMessage.getMessage("car.licensePlate.isExist"), null);
            }
            //保存车辆信息
            carInfoService.save(carInfo);
            //插入日志
            carLogService.addLog(null, carInfo.getId(), "insert");
        } catch (Exception e) {
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            //系统错误
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), new PrintStream(baos));
        }
        return setResultSuccess();
    }

    /**
     * @description 上传图片
     * @author sunyongzheng
     * @date 2021/3/11 11:25
     */
    @RequestMapping(path = "/uploadPicture", method = RequestMethod.POST)
    @ApiOperation(value = "上传图片", notes = "上传图片")
    public ResponseBase uploadPicture(@RequestParam(value = "file", required = true) MultipartFile file) {

        String destName, path, picturePath, datePath;
        //校验图片格式
        if (!file.getContentType().split("/")[0].equals("image")) {
            return setResult(Constants.HTTP_RES_CODE_401, localeMessage.getMessage("car.picture.type.error"), null);
        }
        try {
            //获取文件上传路径
            datePath = new SimpleDateFormat("yyyyMMdd").format(new Date());
            path = this.PICTURE_PATH + File.separator + datePath + File.separator;
            //构建File对象
            File dir = new File(path);
            //判断文件夹是否存在
            if (!dir.exists()) {
                //文件夹不存在则创建
                dir.mkdirs();
            }
            destName = UUID.randomUUID().toString().replace("-", "") + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            //拼接图片上传路径
            picturePath = path + destName;
            //上传图片
            file.transferTo(new File(picturePath));
        } catch (Exception e) {
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            //系统错误
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null);
        }
        Map<String, String> carPicture = new HashMap<>();
        //返回图片信息
        carPicture.put("picturePath", datePath + File.separator + destName);
        return setResultSuccess(carPicture);
    }

    /**
     * @description 删除图片
     * @author sunyongzheng
     * @date 2021/3/19 11:37
     */
    @RequestMapping(path = "/deletePicture", method = RequestMethod.POST)
    @ApiOperation(value = "删除图片", notes = "删除图片")
    public ResponseBase deletePicture(@RequestParam("picture") String picture) throws IOException {

        File file = new File(this.PICTURE_PATH + File.separator + picture);
        DataOutputStream dos = new DataOutputStream(new FileOutputStream(file));
        dos.close();
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                return setResultSuccess();
            } else {
                //删除失败
                return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("car.picture.isNotDelete"), null);
            }
        } else {
            return setResultSuccess();
        }
    }

    /**
     * @description 分页查询车辆列表
     * @author sunyongzheng
     * @date 2021/3/17 17:58
     */
    @ApiOperation(value = "分页查询车辆列表", notes = "分页查询车辆列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPage", value = "当前第几页", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页显示几条", required = true)
    })
    @RequestMapping(value = "/selectCarPage", method = RequestMethod.POST)
    public ResponseBase selectCarPage(@RequestBody CarInfoQuery carInfoQuery, @RequestParam("currentPage") Integer currentPage, @RequestParam("pageSize") Integer pageSize) {
        try {
            Page<CarInfoResult> page = new Page<>(currentPage, pageSize);
            IPage<CarInfoResult> result = carInfoService.selectCarPage(page, carInfoQuery);
            return setResultSuccess(result);
        } catch (Exception e) {
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            //系统错误
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null);
        }
    }

    /**
     * @description 删除车辆
     * @author sunyongzheng
     * @date 2021/3/18 14:41
     */
    @ApiOperation(value = "删除车辆", notes = "删除车辆")
    @RequestMapping(value = "/delCar", method = RequestMethod.GET)
    @Transactional
    public ResponseBase delCar(@RequestParam String id) {
        try {
            //获取更新之前的数据
            QueryWrapper<CarInfo> wrapper = new QueryWrapper();
            wrapper.eq("id", id);
            CarInfo oldInfo = carInfoService.getBaseMapper().selectList(wrapper).get(0);
            //车辆检验
            if (oldInfo.getId().isEmpty()) {
                return setResult(Constants.HTTP_RES_CODE_402, localeMessage.getMessage("sys.common.isNotExist"), null);
            }
            //验证车辆预定状态
            /*if(oldInfo.getCarReserveStatus() == 1){
                return setResult(Constants.HTTP_RES_CODE_402, localeMessage.getMessage("car.isReserved"), null);
            }*/
            //验证车辆使用状态
            if (oldInfo.getCarUseStatus() == 1) {
                return setResult(Constants.HTTP_RES_CODE_402, localeMessage.getMessage("car.isUsed"), null);
            }
            //删除车辆
            carInfoService.removeById(id);
            //插入日志
            carLogService.addLog(oldInfo, id, "delete");
        } catch (Exception e) {
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            //系统错误
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null);
        }
        return setResultSuccess();
    }


    /**
     * @description 修改车辆
     * @author sunyongzheng
     * @date 2021/3/19 17:57
     */
    @ApiOperation(value = "修改车辆", notes = "修改车辆")
    @RequestMapping(value = "/updateCar", method = RequestMethod.POST)
    @Transactional
    public ResponseBase updateCar(@Valid @RequestBody CarInfo carInfo, BindingResult bindingResult) {
        try {
            // 验证实体输入参数
            ResponseBase validResult = validateField(bindingResult);
            if (validResult != null) {
                return validResult;
            }
            //获取更新之前的数据
            QueryWrapper<CarInfo> wrapper = new QueryWrapper();
            wrapper.eq("id", carInfo.getId());
            CarInfo oldInfo = carInfoService.getBaseMapper().selectList(wrapper).get(0);
            //验证车辆预定状态
            /*if(oldInfo.getCarReserveStatus() == 1){
                return setResult(Constants.HTTP_RES_CODE_402, localeMessage.getMessage("car.isReserved"), null);
            }*/
            //验证车辆使用状态
            /*if (oldInfo.getCarUseStatus() == 1) {
                return setResult(Constants.HTTP_RES_CODE_402, localeMessage.getMessage("car.isUsed"), null);
            }*/
            //更新数据
            carInfoService.updateById(carInfo);
            //插入日志
            carLogService.addLog(oldInfo, carInfo.getId(), "update");
        } catch (Exception e) {
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            //系统错误
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null);
        }
        return setResultSuccess();
    }

    /**
     * @description 查询商户信息
     * @author sunyongzheng
     * @date 2021/3/18 16:28
     */
    @ApiOperation(value = "查询商户信息", notes = "查询商户信息")
    @RequestMapping(value = "/selectCompany", method = RequestMethod.GET)
    public ResponseBase selectCompany() {
        try {
            QueryWrapper<CarCompany> wrapper = new QueryWrapper();
            wrapper.eq("is_delete", 0);
            wrapper.orderByDesc("create_time");
            List<CarCompany> resultList = carCompanyService.list(wrapper);
            return setResultSuccess(resultList);
        } catch (Exception e) {
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            //系统错误
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null);
        }
    }

    /**
     * @description 修改预定状态
     * @author sunyongzheng
     * @date 2021/3/23 11:42
     */
    @ApiOperation(value = "修改预定状态", notes = "修改预定状态")
    @RequestMapping(value = "updateReserveStatus", method = RequestMethod.POST)
    public ResponseBase updateReserveStatus(@RequestBody CarInfo carInfo) {
        //校验参数
        if (StringUtils.isEmpty(carInfo.getCarReserveStatus())) {
            return setResult(Constants.HTTP_RES_CODE_401, localeMessage.getMessage("sys.parameter.error"), null);
        }
        try {
            carInfoService.updateById(carInfo);
        } catch (Exception e) {
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            //系统错误
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("car.excel.write.false"), null);
        }
        return setResultSuccess();

    }

    /**
     * @description 查询车辆品牌信息
     * @author sunyongzheng
     * @date 2021/3/25 14:18
     */
    @ApiOperation(value = "查询车辆品牌信息", notes = "查询车辆品牌信息")
    @RequestMapping(value = "selectCarBrand", method = RequestMethod.GET)
    public ResponseBase selectCarBrand(@RequestParam(value = "url", required = true) String url) throws Exception {
        try {
            String newUrl = StringEscapeUtils.unescapeHtml(url);
            String brand = HttpUtil.httpClientDoGet(newUrl);
            JSONObject jsonObject = JSONObject.parseObject(brand);
            return setResultSuccess(jsonObject);
        } catch (Exception e) {
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.parameter.error"), null);
        }


    }

    /**
     * @description 添加预定
     * @author sunyongzheng
     * @date 2021/3/23 15:46
     */
    @ApiOperation(value = "添加预定", notes = "添加预定 ")
    @RequestMapping(value = "/addReserveInfo", method = RequestMethod.POST)
    @Transactional
    public ResponseBase addReserveInfo(@Valid @RequestBody CarReserveInfo carReserveInfo, BindingResult bindingResult) {
        try {
            // 验证实体输入参数
            ResponseBase validResult = validateField(bindingResult);
            if (validResult != null) {
                return validResult;
            }
            //校验车辆是否被预定
            CarInfo carCheck = carInfoService.getById(carReserveInfo.getCarId());
            if (carCheck.getCarReserveStatus() == 1) {
                return setResult(Constants.HTTP_RES_CODE_402, localeMessage.getMessage("car.isReserved"), null);
            }
            //设置预定状态
            carReserveInfo.setReserveStatus(1);
            boolean flag = carReserveInfoService.save(carReserveInfo);
            /*if(flag){
                CarInfo carInfo = new CarInfo();
                carInfo.setId(carReserveInfo.getCarId());
                carInfo.setCarReserveStatus(1);
                carInfoService.updateById(carInfo);
            }*/
        } catch (Exception e) {
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            //系统错误
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), new PrintStream(baos));
        }
        return setResultSuccess();
    }


    /**
     * @description 车辆查重
     * @author sunyongzheng
     * @date 2021/3/26 10:09
     */
    public boolean duplicateChecking(String name, String value) {
        try {
            //添加自定义查询参数
            QueryWrapper<CarInfo> wrapper = new QueryWrapper();
            wrapper.eq("is_delete", 0);
            wrapper.eq(name, value);
            List<CarInfo> result = carInfoService.getBaseMapper().selectList(wrapper);
            if (result.size() > 0) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            //系统错误
            return true;
        }

        return false;
    }


}
